const { router, fs, urlencodedParser } = require('../CustomMethod');
const axios = require('axios');
const cheerio = require('cheerio');
const bodyParser = require('body-parser');
const cors = require('cors');

router.use(bodyParser.json());
router.use(cors());

router.post('/shopping', urlencodedParser, (req, res) => {
    const query = req.body.query;
    const url = `https://search.suning.com/${query}/`;
    axios.get(url, {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }
    })
        .then(response => {
            const html = response.data;
            const $ = cheerio.load(html);
            const products = [];

            $('.product-box').each((i, elem) => {
                const title = $(elem).find('.title-selling-point').text().trim();
                const img = $(elem).find('.img-block img').attr('src');
                const link = $(elem).find('a').attr('href');
                const pinjia = $(elem).find('i').text().trim();
                products.push({ title, img, link, pinjia });
            });
            res.send({ code: 200, module: products });
        })
        .catch(error => {
            console.error('获取数据时出错:', error);
            res.status(500).json({ error: '获取数据时出错' });
        });
});

module.exports = router
